package com.xiaozhen.jt809.handler.server;

import com.xiaozhen.common.redis.utils.RedisUtils;
import com.xiaozhen.jt809.constant.JT809BusinessConstant;
import com.xiaozhen.jt809.constant.JT809ReqCodeConstants;
import com.xiaozhen.jt809.domain.JT809MessageInfo;
import com.xiaozhen.jt809.handler.MyHandler;
import com.xiaozhen.jt809.server.TcpClient;
import com.xiaozhen.jt809.utils.ByteArrayUtil;
import com.xiaozhen.jt809.utils.ResponseUtil;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/15 11:48
 * @description:
 */
@Slf4j
@Service
public class UpConnectHandler implements MyHandler {

    @Autowired
    private TcpClient tcpClient;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void handler(ChannelHandlerContext ctx, JT809MessageInfo messageInfo) {
        try {
            this.login(ctx, messageInfo);
        } catch (Exception e) {
            log.error("登录异常");
        }
    }

    public void login(ChannelHandlerContext ctx, JT809MessageInfo messageInfo) throws Exception {
        log.info("正在登录");
        int offset = 0;
        byte[] messageBody = messageInfo.getMessageBody();
        //用户名
        int userId = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(messageBody, offset, 4));
        offset += 4;
        //密码
        String password = ByteArrayUtil.bytes2gbkString(ByteArrayUtil.subBytes(messageBody, offset, 8));
        password = password.replaceAll("\\u0000", "");
        offset += 8;
        //下级平台提供的从链路连接IP地址
        String downLinkIp = ByteArrayUtil.bytes2gbkString(ByteArrayUtil.subBytes(messageBody, offset, 32));
        downLinkIp = downLinkIp.replaceAll("\\u0000", "");
        offset += 32;
        //下级平台提供的从链路连接端口号
        int downLinkPort = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(messageBody, offset, 2));
        offset += 2;

        //校验IP地址
        //校验接入码
        //用户名
        //密码
        //检验连接已经占用
        //接入成功
        byte[] result = new byte[]{JT809ReqCodeConstants.UpConnect.SUCCESS};
        byte[] verifyCode = new byte[4];
        byte[] responseBody = ByteArrayUtil.append(result, verifyCode);
        //设置返回消息
        JT809MessageInfo responseMessage = ResponseUtil.responseMessage(messageInfo,
                JT809BusinessConstant.UP_CONNECT_RSP,
                responseBody);
        ctx.writeAndFlush(responseMessage);
        //主链路连接成功 发起从链路连接请求
        log.info("登录成功");
        Thread.sleep(1000L);
        //将从链路登录信息放到redis
        redisUtils.set(downLinkIp + ":" + downLinkPort, messageInfo);
        //启动从链路
        tcpClient.runClient(downLinkIp, downLinkPort);
    }

}
